<?php
/**
 * Special price offer
 *
 * @author Lukas Normantas
 */
class Catalog_Model_Special extends Doctrine_Record
{
    public function setTableDefinition()
    {
        $this->setTableName('catalog_specials');
        $this->hasColumn('product_id', 'integer');
        $this->hasColumn('price', 'float');
        $this->hasColumn('start_at', 'date');
        $this->hasColumn('end_at', 'date');
    }

    public function setUp()
    {
        $this->actAs('Timestampable');
        $this->hasOne('Catalog_Model_Product as Product', array(
            'local' => 'product_id',
            'foreign' => 'id'
        ));
    }

    public function getCurrentSpecialProductList()
    {
        return 
            Doctrine_Query::create()
                ->select('s.*, p.*')
                ->from( 'Catalog_Model_Product p' )
                ->leftJoin( 'p.Specials s' )
                ->addWhere('s.start_at <= CURRENT_DATE AND s.end_at>=CURRENT_DATE')
                ->andWhere('p.active = ?', 1)
                ->orderBy( 'p.title' )->execute(null, Doctrine::HYDRATE_ARRAY);
    }


    /**
     * @var Zend_Form
     */
    protected $_editingForm = null;

    public function getEditingForm(){
        if ($this->_editingForm == null){
            $this->_editingForm = new Catalog_Form_SpecialEditing();
            $this->_editingForm->setDefaults($this->toArray());
        }
        return $this->_editingForm;
    }

    public function edit($data)
    {
        $form = $this->getEditingForm();
        if ($form->isValid( $data )){
            $this->fromArray( $form->getValues() );
            $this->save();            
            return true;
        } 
        return false;
    }    
}